package com.jobs.service;

import com.jobs.event.MyEvent;
import com.jobs.pojo.Customer;
import com.jobs.repositories.CustomerCrudRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @Author 王博
 * @DateTime 2024-07-05 13:37
 */
@Component
@Slf4j
public class CustomerService {

    @Resource
    private CustomerCrudRepository customerRepository;
    @Resource
    private ApplicationContext applicationContext;
    @Transactional
    public void save(Customer customer) {
        customerRepository.save(customer);
        log.info("save保存客户成功：新客户id为："+customer.getId());
        applicationContext.publishEvent(new MyEvent("myevent"));
    }

    @Async
    @EventListener
//    @Transactional
    public void save2(MyEvent event) {
        Customer customer  = new Customer();
        customer.setName("另一个事务");
        customerRepository.save(customer);
        log.info("save2接收到的事件内容为："+event.getMsg());
        throw new RuntimeException("测试事务");
    }
}
